<template>
    <Fluid>


        <div class="flex mt-8">
            <div class="card flex flex-col gap-4 w-full">
                <div class="font-semibold text-xl">
                    照片 (可以在支付宝里搜索‘证件照’小程序免费制作证件照)
                </div>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex flex-col gap-2 w-full">
                        <InputText type="file" id="screenshot0" @change="onUploadImage($event, 'displayImage')"
                            accept="image/*" style="display: none" />
                        <img id="displayImage" ref="faceImageRef"
                            :src="formData.FaceData ? formData.FaceData : formData.Face" width="100%"
                            style="max-height: 100px; max-width: 100px; border-radius: 4px"
                            onclick=" document.getElementById('screenshot0').click();" />
                        <span>头像(用于社交互动)</span>
                    </div>
                    <div class="flex flex-col gap-2 w-full">
                        <InputText type="file" id="screenshot1" @change="onUploadImage($event, 'yicun')"
                            accept="image/*" style="display: none" />
                        <img id="yicun" ref="yicunRef" :src="formData.yicunData ? formData.yicunData : formData.Yicun"
                            width="100%" style="max-height: 100px; max-width: 100px; border-radius: 4px"
                            onclick=" document.getElementById('screenshot1').click();" />
                        <span>1寸照(用于学生证件)</span>
                    </div>
                    <div class="flex flex-col gap-2 w-full">
                        <InputText type="file" id="screenshot2" @change="onUploadImage($event, 'liangcun')"
                            accept="image/*" style="display: none" />
                        <img id="liangcun" ref="liangcunRef"
                            :src="formData.liangcunData ? formData.liangcunData : formData.Liangcun" width="100%"
                            style="max-height: 100px; max-width: 100px; border-radius: 4px"
                            onclick=" document.getElementById('screenshot2').click();" />
                        <span>2寸照(用于学生证件)</span>
                    </div>
                </div>
                <div class="font-semibold text-xl">个人资料</div>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Name">姓名</label>
                        <InputText id="Name" ref="firstname2Ref" v-model="formData.Name" type="text" />
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Sn">学号</label>
                        <InputText id="Sn" :value="formData.Sn" disabled> </InputText>
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="En_Name">英文名</label>
                        <InputText id="En_Name" ref="enNameRef" v-model="formData.EnName" type="text" />
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Tel">电话号码</label>
                        <InputText id="Tel" ref="telRef" v-model="formData.Tel" type="text" />
                    </div>
                </div>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Grade">年级</label>
                        <InputText id="Grade" ref="gradeRef" v-model="formData.Grade" type="text" />
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="sex">性别</label>
                        <div class="flex items-center">
                            <RadioButton id="option1" name="sex" value="男" v-model="formData.Sex" />
                            <label for="option1" class="leading-none ml-2">男</label>
                        </div>
                        <div class="flex items-center">
                            <RadioButton id="option2" name="sex" value="女" v-model="formData.Sex" />
                            <label for="option2" class="leading-none ml-2">女</label>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Birthday">生日</label>
                        <InputText id="Birthday" ref="birthdayRef" v-model="formData.Birthday" type="date" />
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Qq">QQ</label>
                        <InputText id="Qq" ref="qqRef" v-model="formData.Qq" type="text" aria-required="true" />
                    </div>
                </div>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Email">邮箱</label>
                        <InputText id="Email" ref="emailRef" v-model="formData.Email" type="text" />
                    </div>
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Address">家庭住址</label>
                        <InputText id="Address" ref="addressRef" v-model="formData.Address" type="text" />
                    </div>
                </div>
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex flex-wrap gap-2 w-full">
                        <label for="Desc">描述</label>
                        <Textarea id="Desc" ref="descRef" v-model="formData.Desc" rows="4" />
                    </div>
                </div>
                <div class="flex flex-col md:flex-row gap-4">
                    <Button label="提交" @click="handleSubmit" />
                    <Button label="重置" severity="warn" @click="handleReset" />
                    <Button label="参与抽奖" severity="success" @click="canyushoujiaing" />
                </div>
            </div>
        </div>
    </Fluid>
    <Toast />
</template>

<script setup>
import { UserService } from "@/service/UserService";
import { apiClient } from '@/utils/apiClient';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { CommonService } from "../common";
const route = useRoute();
const faceImageRef = (ref < HTMLImageElement) | (null > null);
const yicunRef = (ref < HTMLImageElement) | (null > null);
const liangcunRef = (ref < HTMLImageElement) | (null > null);
const firstname2Ref = (ref < HTMLInputElement) | (null > null);
const lastname2Ref = (ref < HTMLInputElement) | (null > null);
const enNameRef = (ref < HTMLInputElement) | (null > null);
const telRef = (ref < HTMLInputElement) | (null > null);
const gradeRef = (ref < HTMLInputElement) | (null > null);
const birthdayRef = (ref < HTMLInputElement) | (null > null);
const qqRef = (ref < HTMLInputElement) | (null > null);
const emailRef = (ref < HTMLInputElement) | (null > null);
const addressRef = (ref < HTMLInputElement) | (null > null);
const descRef = (ref < HTMLTextAreaElement) | (null > null);


const formData = ref({
    Name: "",
    Sn: "",
    EnName: "",
    Tel: "",
    Grade: "",
    Birthday: "",
    Qq: "",
    Email: "",
    Address: "",
    Desc: "",
    Pswd: "",
    Sex: "",
    Face: "",
    Yicun: "",
    Liangcun: "",
    FaceData: "",
    yicunData: "",
    liangcunData: "",
});

onMounted(() => {
    handleReset();
});

function canyushoujiaing() {
    // 使用apiClient直接调用API，自行处理响应格式
    apiClient.get('/api/records/canyuChoujiang')
        .then(function (response) {
            // 根据实际返回的数据格式进行判断
            // 成功格式: {"Title": "参与抽奖成功","Data": {"name": "罗楠","sn": "58243586"},"Code": 1000}
            if (response.Code === 1000) {
                const data = response.Data;
                let toast;
                try {
                    toast = useToast();
                } catch (e) {
                    console.warn('PrimeVue Toast 服务不可用:', e.message);
                }

                if (toast) {
                    toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: data.name + "报名抽奖成功",
                        life: 3000
                    });
                } else {
                    // 降级处理：使用alert
                    alert(data.name + "报名抽奖成功");
                }
                // route.push('/choujiang');
            } else {
                // 处理其他可能的错误情况
                let toast;
                try {
                    toast = useToast();
                } catch (e) {
                    console.warn('PrimeVue Toast 服务不可用:', e.message);
                }

                if (toast) {
                    toast.add({
                        severity: 'error',
                        summary: '错误',
                        detail: response.Title || '参与抽奖失败',
                        life: 5000
                    });
                } else {
                    // 降级处理：使用alert
                    alert(response.Title || '参与抽奖失败');
                }
            }
        })
        .catch(function (error) {
            let toast;
            try {
                toast = useToast();
            } catch (e) {
                console.warn('PrimeVue Toast 服务不可用:', e.message);
            }

            if (toast) {
                toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '参与抽奖请求失败: ' + (error.message || '未知错误'),
                    life: 5000
                });
            } else {
                // 降级处理：使用alert
                alert('参与抽奖请求失败: ' + (error.message || '未知错误'));
            }
        });
}
// 监听 formData 的变化并存储到 localStorage

function onUploadImage(e, name) {
    const file = e.target.files[0];
    if (file) {
        if (file.size > 512 * 1024) {
            const reader = new FileReader();
            reader.onload = function (event) {
                const img = new Image();
                img.onload = function () {
                    const canvas = document.createElement("canvas");
                    const MAX_WIDTH = 800; // 定义最大宽度
                    const MAX_HEIGHT = 600; // 定义最大高度
                    let width = img.width;
                    let height = img.height;
                    if (width > MAX_WIDTH) {
                        height = (height * MAX_WIDTH) / width;
                        width = MAX_WIDTH;
                    }
                    if (height > MAX_HEIGHT) {
                        width = (width * MAX_HEIGHT) / height;
                        height = MAX_HEIGHT;
                    }
                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext("2d");
                    ctx.drawImage(img, 0, 0, width, height);
                    const compressedDataUrl = canvas.toDataURL(file.type, 0.7);
                    if (name === "displayImage") {
                        faceImageRef.value?.setAttribute("src", compressedDataUrl);
                        // 问：下面的formData.value.displayImageData  格式是base64编码吗
                        formData.value.FaceData = compressedDataUrl;
                    } else if (name === "yicun") {
                        yicunRef.value?.setAttribute("src", compressedDataUrl);

                        formData.value.yicunData = compressedDataUrl;
                    } else if (name === "liangcun") {
                        liangcunRef.value?.setAttribute("src", compressedDataUrl);

                        formData.value.liangcunData = compressedDataUrl;
                    }
                };
                img.setAttribute("src", event.target.result + "");
            };
            reader.readAsDataURL(file);
        } else {
            const reader = new FileReader();
            reader.onload = function (event) {
                if (name === "displayImage") {
                    faceImageRef.value?.setAttribute("src", event.target.result + "");
                    // 存储未压缩的图像数据
                    formData.value.FaceData = event.target.result + "";
                } else if (name === "yicun") {
                    yicunRef.value?.setAttribute("src", event.target.result + "");
                    // 存储未压缩的图像数据
                    formData.value.yicunData = event.target.result + "";
                } else if (name === "liangcun") {
                    liangcunRef.value?.setAttribute("src", event.target.result + "");
                    // 存储未压缩的图像数据
                    formData.value.liangcunData = event.target.result + "";
                }
            };
            reader.readAsDataURL(file);
        }
    }
}

function handleSubmit() {

    //奇怪编写updateInfo formData.value 中包含多张图片，和其他字符串以及int数据，
    UserService.updateInfo(formData.value.Sn, formData.value)
        .then((result) => {
            // 处理更新成功的情况
            if (result.Code != 1000) {
                alert(result.Title);
            } else {
                alert(result.Title);
            }
            const loginUser = localStorage.getItem("user");
            console.log(JSON.parse(loginUser).Sn, formData.value.Sn);
            if (JSON.parse(loginUser).Sn == formData.value.Sn) {
                localStorage.setItem("user", JSON.stringify(result.Data));
            }
        })
        .catch((error) => {
            alert("更新用户信息出错");
            // handleError({ Title: "更新用户信息出错", Code: -1 });
        });

    // 可以在这里将 formData.value 发送到服务器或进行其他处理
}

function handleReset() {
    const snStr = String(route.params.sn);
    UserService.getUserInfo(snStr)
        .then((result) => {
            // 处理更新成功的情况
            if (result.Code != 1000) {
                alert(result.Title);
                return;
            } else {
                const parsedData = result.Data;
                formData.value = parsedData;
                formData.value.Birthday = CommonService.formatDate(parsedData.Birthday);
            }
        })
        .catch((error) => {
            alert("获取用户信息出错" + error);
        });
}
</script>

<style>
fieldset {
    border: 2px #ffffff solid;
    border-radius: 5px;
    padding: 1rem;
}

legend {
    padding: 0.8rem;
}
</style>
